package com.yunshipei.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.common.Globals;
import com.yunshipei.model.UserInfo;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.HeadName;
import com.yunshipei.model.QuitGroupModel;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.activity.DetailContactsActivity;
import com.yunshipei.ui.view.widget.MyGridView;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import io.rong.app.DemoContext;
import io.rong.app.activity.FriendListActivity;
import io.rong.app.activity.GroupMainPageActivity;
import io.rong.app.adapter.ImageAdapter;
import io.rong.app.model.GroupCreateInfo;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;

/**
 * Created by cike on 16/9/9.
 */
public class GroupMemberFragment extends Fragment {
    private MyGridView gridView;
    private GroupCreateInfo mApiResult;
    private ImageAdapter imageAdapter;
    private boolean groupState = true;
    private int gridSize = 18;
    private String groupCreateId = "";
    private List<HeadName> data;
    private SharedPreferences mySharedPreferences;
    private DatabaseUtil dataUtil;
    private static final int REQUSET = 1;

    public void setGroupCreateInfo(GroupCreateInfo mApiResult) {
        this.mApiResult = mApiResult;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mySharedPreferences = getActivity().getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.group_member_fragment, null);
        gridView = (MyGridView) view.findViewById(R.id.avatar_grid);
        return view;
    }

    @Override
    public void onStart() {
        groupCreateId = mApiResult.getCreate_user_id();
        data = getAvatarList(mApiResult.getGourpMembers(), groupCreateId);
        //判断群主状态
        if (groupCreateId != null && groupCreateId.equals(mySharedPreferences.getString("uuid", ""))) {
            groupState = true;
        } else {
            groupState = false;
        }
        imageAdapter = new ImageAdapter(getActivity(), data, groupState);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridView.setAdapter(imageAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                onItemClickListner(arg0, arg1, arg2, arg3);
            }
        });
        super.onStart();
    }

    private void onItemClickListner(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

        ImageAdapter adapter = (ImageAdapter) gridView.getAdapter();
        if (arg2 == adapter.getSize() + 1 && adapter.getState()) {
            //转为删除状态
//            if (!adapter.getRemoveState()) {
//                adapter.setRemoveState(true);
//            } else {
//                adapter.setRemoveState(false);
//            }
//            adapter.notifyDataSetChanged();
            deleteGroupMember();
            //通知隐藏删除图标
        } else if (arg2 == adapter.getSize()) {
            if (adapter.getRemoveState()) {
                //转为正常状态
                adapter.setRemoveState(false);
                adapter.notifyDataSetChanged();
            } else {
                addNewmember();
            }
        } else if (arg2 < adapter.getSize()) {
            if (adapter.getRemoveState()) {
                // 点击就从群中删除此人
//                deleteMember(adapter, arg2);
            } else {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                UserInfo userInfo = dataUtil.queryUserInfoByid(data.get(arg2).getUuid());
                if (userInfo != null) {
                    bundle.putSerializable("userInfo", userInfo);
                    intent.putExtras(bundle);
                    intent.setClass(getActivity(), DetailContactsActivity.class);
                    startActivity(intent);
                }
            }
        }
    }

    private void deleteGroupMember() {
        Intent intent = new Intent(getActivity(), FriendListActivity.class);
        intent.putExtra("uuids", mApiResult.getGourpMembers());
        Bundle bundle = new Bundle();
        bundle.putInt(FriendListActivity.STATE, 3);
        intent.putExtra(FriendListActivity.FROMHERE, bundle);
        intent.putExtra("gid", mApiResult.getId());
        startActivityForResult(intent, REQUSET);
    }

    public void addNewmember() {
        if (mApiResult.getNumber() < Globals.GROUPMAX) {
            Intent intent = new Intent(getActivity(), FriendListActivity.class);
            intent.putExtra("uuids", mApiResult.getGourpMembers());
            Bundle bundle = new Bundle();
            bundle.putInt(FriendListActivity.STATE, 2);
            intent.putExtra(FriendListActivity.FROMHERE, bundle);
            intent.putExtra("gid", mApiResult.getId());
            this.startActivityForResult(intent, REQUSET);
        } else {
            Toast.makeText(getActivity(), "群组成员上限为" + Globals.GROUPMAX + "人", Toast.LENGTH_LONG).show();
        }
    }

    /*
   获取群组成员列表
    */
    public List<HeadName> getAvatarList(String originalStr, String groupCreateId) {
        List<HeadName> list = new ArrayList<>();
        dataUtil = new DatabaseUtil();
        try {
            JSONArray groupMemIdArray = new JSONArray(originalStr);
            int length = groupMemIdArray.length();
            if (gridSize != 0 && length > gridSize) {
                length = gridSize;
            }
            for (int i = 0; i < length; i++) {
                HeadName hName = new HeadName();
                io.rong.imlib.model.UserInfo userInfo = dataUtil.queryByUuid(groupMemIdArray.getString(i));
                if (userInfo != null) {
                    hName.setUuid(userInfo.getUserId());
                    hName.setName(userInfo.getName());
                    if (userInfo.getPortraitUri() != null) {
                        hName.setAvatarUri(userInfo.getPortraitUri().toString());
                    }
                    if (!TextUtils.isEmpty(userInfo.getUserId()) && userInfo.getUserId().equals(groupCreateId)) {
                        list.add(0, hName);
                    } else {
                        list.add(hName);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    public void setUserData(GroupCreateInfo mApiResult) {
        this.mApiResult = mApiResult;
    }

    /**
     * update avatorGrid
     *
     * @param quitGroupModel
     */
    public void onEventMainThread(QuitGroupModel quitGroupModel) {
        if (quitGroupModel != null) {
            mApiResult = DemoContext.getInstance(getActivity()).getOneResult(quitGroupModel.getGroupId());
            imageAdapter = (ImageAdapter) gridView.getAdapter();
            imageAdapter.clear();
            imageAdapter.add(getAvatarList(mApiResult.getGourpMembers(), mApiResult.getCreate_user_id()));
            ((GroupMainPageActivity) getActivity()).setGroupCreateInfo(mApiResult);
        }
    }

    public void onEventMainThread(YspEvent.DeleteGroupMember deleteGroupMember) {
        mApiResult.setGourpMembers(deleteGroupMember.getUuids());
        data = getAvatarList(deleteGroupMember.getUuids(), deleteGroupMember.getGid());
        imageAdapter.clear();
        imageAdapter.add(data);
        ((GroupMainPageActivity) getActivity()).setGroupCreateInfo(mApiResult);
        ((GroupMainPageActivity) getActivity()).setGroupNember(data.size());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        String result;
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        //requestCode标示请求的标示   resultCode表示有数据
        if (requestCode == this.REQUSET && resultCode == getActivity().RESULT_OK) {
            HashMap<String, String> map = new HashMap<>();
            String newUuids = data.getStringExtra(FriendListActivity.NEWUUIDS);
            String newAmount = data.getStringExtra(FriendListActivity.NEWAMOUNT);
            String uuids[] = newUuids.split(",");
            List<String> list = Arrays.asList(uuids);
            System.out.println("uuids-Length" + uuids.length);
            List<HeadName> headName = new ArrayList<>();
            for (String str : list) {
                DatabaseUtil dataUtil = new DatabaseUtil();
                HeadName hName = new HeadName();
                io.rong.imlib.model.UserInfo userInfo = dataUtil.queryByUuid(str);
                hName.setUuid(userInfo.getUserId());
                hName.setName(userInfo.getName());
                if (userInfo.getPortraitUri() != null) {
                    hName.setAvatarUri(userInfo.getPortraitUri().toString());
                }
                result = StringUtilSub.addNewMemberUuid(mApiResult.getGourpMembers(), str);
                mApiResult.setGourpMembers(result);
                headName.add(hName);
            }
            int imageAdapterSize = imageAdapter.getData().size();
            if (imageAdapterSize < gridSize && (gridSize - imageAdapterSize) < headName.size()) {
                imageAdapter.add(headName.subList(0, gridSize - imageAdapterSize));
            } else if (imageAdapterSize < gridSize) {
                imageAdapter.add(headName);
            }
            ((GroupMainPageActivity) getActivity()).setGroupNember(mApiResult.getGourpMembers().split(",").length);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}